package main

import (
	"errors"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

func main() {
	var port string // 输入要关闭的端口号
	fmt.Print("请输入要关闭的端口号：")
	_, err := fmt.Scanln(&port)
	if err != nil {
		return
	}
	closePort(port)
}

func closePort(port string) {
	sysOs := runtime.GOOS
	var content string
	var err error
	switch sysOs {
	case "darwin":
		content, err = macClosePort(port)
	case "windows":
		content, err = winClosePort(port)
	case "linux":
		content, err = linuxClosePort(port)
	default:
		err = errors.New("this system is not supported at this time！")
	}

	if err != nil {
		log.Println("关闭端口失败", err)
	} else {
		log.Println("成功关闭端口", content)
	}
	fmt.Printf("按任意键退出...")
	for {
		b := make([]byte, 1)
		_, err = os.Stdin.Read(b)
		if err != nil {
			fmt.Printf(err.Error())
		} else {
			return
		}
	}
}

func winClosePort(port string) (string, error) {
	c1 := exec.Command("powershell.exe", "netstat", "-ano", "| findstr", port, "| findstr", "LISTENING")
	output, err := c1.CombinedOutput()
	if err != nil {
		return "", err
	}
	decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(output)
	strNetstat := string(decodeBytes)

	Pid := "0"

	for _, v := range strings.Split(strNetstat, "\r\n") {
		for {
			if strings.Contains(v, "  ") {
				v = strings.ReplaceAll(v, "  ", " ")
			} else {
				break
			}
		}
		strings.Trim(v, " ")

		arrTmp := strings.Split(v, " ")
		arr := make([]string, 0)
		for _, vv := range arrTmp {
			if vv != "" {
				arr = append(arr, vv)
			}
		}
		if len(arr) == 5 && fmt.Sprintf("0.0.0.0:%v", port) == arr[1] {
			Pid = arr[4]
			break
		}
	}

	if Pid == "0" {
		return "", errors.New(fmt.Sprintf("No service with port number %v found", port))
	}

	c2 := exec.Command("powershell.exe", "taskkill -f -pid ", Pid)
	output, err = c2.CombinedOutput()
	if err != nil {
		return "", err
	}
	decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(output)
	delStr := string(decodeBytes)
	return delStr, nil
}

func linuxClosePort(port string) (string, error) {
	cmd := exec.Command("fuser", "-k", "-n", "tcp", port)
	err := cmd.Run()
	if err != nil {
		return port, err
	}
	return port, nil
}

func macClosePort(port string) (string, error) {
	cmd := exec.Command("lsof", "-i", ":"+port)
	output, err := cmd.Output()
	if err != nil {
		fmt.Println("Error:", err)
		return port, err
	}

	lines := strings.Split(string(output), "")
	for _, line := range lines {
		if strings.Contains(line, port) {
			fields := strings.Fields(line)
			pid := fields[1]
			err := killProcess(pid)
			if err != nil {
				fmt.Println("Error:", err)
			} else {
				fmt.Printf("成功关闭端口 %s 对应的进程 %s", port, pid)
			}
		}
	}
	return port, nil
}

func killProcess(pid string) error {
	cmd := exec.Command("kill", "-9", pid)
	err := cmd.Run()
	return err
}
